<style scoped lang="scss">
    .avatar-uploader ::v-deep .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader ::v-deep .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 150px;
        height: 150px;
        line-height: 150px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .demo-model {

    }
</style>

<template>
    <div class="page">
        <el-form :model="model" :rules="rules" v-loading="loading" ref="editForm" label-width="70px"
                 class="demo-model">
            <el-row :gutter="30" style="margin-bottom: 0">
                <el-col :span="16">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="model.title" clearable maxlength="150" show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item label="SEO标题" prop="seoTitle">
                        <el-input v-model="model.seoTitle" clearable maxlength="150" show-word-limit></el-input>
                    </el-form-item>
	                <el-form-item label="权重词" prop="rankKeywords">
		                <el-input v-model="model.rankKeywords" placeholder="具有权重的词，只能设一个，其它文章会自动生成外链" clearable maxlength="150" show-word-limit></el-input>
	                </el-form-item>
                    <el-form-item label="内容" prop="content" style="height: 506px;">
                        <vue-ueditor-wrap v-model="model.content" :config="defaultUEditorConfig" @ready="ueReady"></vue-ueditor-wrap>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="分类" prop="categoryId">
                        <el-cascader style="width: 100%"
                                     v-model="model.categoryId"
                                     :options="categories"
                                     :props="{ multiple: false, checkStrictly: true,label:'name',value:'id', emitPath:false, expandTrigger:'hover' }"
                                     clearable></el-cascader>
                    </el-form-item>
                    <el-form-item label="标签" prop="tagIDsOrNewTagNames">
                        <el-select
                                v-model="model.tagIDsOrNewTagNames"
                                multiple
                                filterable
                                clearable
                                allow-create
                                default-first-option
                                placeholder="请选择文章标签" style="width: 100%">
                            <el-option
                                    v-for="item in tags"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="属性">
                        <el-checkbox v-model="model.recommend">推荐</el-checkbox>
                        <el-checkbox v-model="model.onlySpider">仅供蜘蛛引流</el-checkbox>
	                    <el-checkbox v-model="model.focus">焦点图</el-checkbox>
                    </el-form-item>

                    <el-form-item label="摘要" prop="description">
                        <el-input type="textarea" v-model="model.description" clearable maxlength="300" show-word-limit
                                  :rows="7"></el-input>
                    </el-form-item>
                    <el-form-item label="缩略图" prop="image">
                        <div>
                            <el-input v-model="model.image" max-length="150" clearable></el-input>
	                        <div style="display: flex; flex-direction: row; justify-items: center">
	                            <el-upload
	                                    class="avatar-uploader"
	                                    accept="image/jpeg,image/gif,image/png"
	                                    :action="eleUploadUrl"
	                                    name="upfile"
	                                    :show-file-list="false"
	                                    :on-success="uploadSuccess"
	                                    :before-upload="uploadSuccess" style="margin-top: 15px; line-height: normal">
	                                <img v-if="model.image" :src="model.image" class="avatar"/>
	                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
	                            </el-upload>
		                        <div style="flex: 1; padding: 15px 0 0 20px;">
			                        <el-button plain @click="chooseImage">从内容中选取封面图</el-button>
		                        </div>
	                        </div>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="large" @click="submitForm" style="width: 100%">提交</el-button>
                    </el-form-item>
                </el-col>
            </el-row>


        </el-form>
    </div>
</template>

<script>
	import VueUeditorWrap from 'vue-ueditor-wrap'

	let pagerHeader = {
		title: '添加/修改文章',
		desc: '请根据文章所在栏目是否需要显示缩略图来决定是否上传缩略图； 根据文章列表页是否需要显示摘要来决定是否填写摘要，摘要一般200字以内；',
		breadcrumb: ['文章', '文章编辑']
	}
	let modelStr = JSON.stringify({
		title: null,
		seoTitle: null,
		rankKeywords:null,
		description: '',
		content: '',
		image: null,
		sortRank: 0,
		recommend: false,
		onlySpider: false,
		focus: false,
		//categoryIds: [],
		categoryId:null,
		tagIDsOrNewTagNames: [],
		id: null, // guid
	})
	export default {
		name: 'articleEdit',
		components: {VueUeditorWrap},
		data() {
			return {
				loading: false,

				categories: [],
				tags: [],
				//uploadUrl: 'http://localhost:856/ueditor/test',

				model: JSON.parse(modelStr),
				rules: {
					title: [
						{required: true, message: '请输入标题', trigger: 'blur'},
					],
					/*image: [
                        { required: true, message: '请上传缩略图', trigger: 'blur' }
                    ],*/
					categoryId: [
						{required: true, message: '请选择分类', trigger: 'blur'},
					],
					/*categoryIds: [
						{required: true, message: '请选择分类', trigger: 'blur'},
						{
							validator: (rule, value, callback) => {
								if (value.length === 0) {
									callback(new Error('请选择分类'));
								} else {
									callback();
								}
							}, trigger: 'change'
						}
					],*/
					/* summary: [
                         {required: true, message: '请输入摘要', trigger: 'blur'},
                         {min: 50, max: 200, message: '长度在 50 到 200 个字符', trigger: 'blur'}
                     ],*/
					content: [
						{required: true, message: '请输入内容', trigger: 'blur'}
					]
				}
			}
		},
		watch:{
			"model.content":function(v){
				if(v){
					//生成摘要
					var str = v.replace(/<\/?.+?>/g,"").replace(/\s/g,"").replace(/\&.+;/g,"");
					if(str && !this.model.description)
					{
						this.model.description = str.substr(0,180);
					}
				}
			}
		},
		activated() {
			this.initForm();
		},
		created() {
			this.initBase();
			this.initForm();
		},
		methods: {
            ueReady(ue){
                let that = this;
                ue.execCommand('serverparam', function(editor) {
                    return {
                        'dir': '' //设置富文本编辑器请求时，携带的额外参数
                    };
                });
            },
			initBase() {
				//获取分类数据
				this.$apis.articles.getCategoryTreeList().then(r => {
					this.categories = r.result;
				}).catch(e => {
				})
				//获取标签数据
				this.$apis.articles.getSimpleTags({page: 1, size: 1000}).then(r => {
					this.tags = r.result.items;
				}).catch(e => {
				})
			},
			initForm() {
				let id = this.$route.query.id;
				if(id)
					pagerHeader.title='修改文章'
                else
					pagerHeader.title='添加文章'
				this.setPageHead(pagerHeader);
				//修改文章

				if (id) {
					// id和之前不一样的时候就重新加载文章进来,一样就不管
					if (id !== this.model.id) {
						this.loading=true;
						this.$apis.articles.getArticle(this.$route.query.id).then(r => {
							this.loading=false;
							if (r.success) {
								this.$refs.editForm.resetFields()
								this.model = r.result;
								this.model.tagIDsOrNewTagNames = this.model.tagIDsOrNewTagNames.map(x => Number(x))
							} else {
								this.$msg.alert.error(r.error.message)
							}
						}).catch(e => {
							this.loading=false;
						})
					}
				} else {
					if (this.model.id) {
						//之前model里面存着id，说明之前是修改文章未完，则清空表单
						this.model = JSON.parse(modelStr);
					}
				}
			},
			chooseImage(){
				var v= this.model.replaceContent? this.model.replaceContent : this.model.content;
				if(!v) return;
				//提取封面图
				var reg = /<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim;
				var arr = [];
				let tem;
				while (tem = reg.exec(v)) {
					arr.push(tem[2]);
				}
				if(arr.length>0 && !this.model.image)
					this.model.image = arr[0];
				// todo 后期可以做成选图
			},
			submitForm() {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.loading = true
						this.$apis.articles.save(this.model).then(r => {
							this.loading = false
							if (r.success) {
								if (this.model.id) {
									this.$msg.notify.success('修改成功');
									this.closeCurrTabAndGoToUrl('/articles');
								} else {
									this.$msg.notify.success('添加成功');
									this.resetForm();
								}
							} else {
								this.$msg.alert.error(r.error.message)
							}
						}).catch(e => {
							console.log(e)
							this.loading = false
						})
					}
				})
			},
			resetForm() {
				this.model = JSON.parse(modelStr);
				this.$nextTick(() => {
					this.$refs.editForm.clearValidate()
				})
			},

			uploadSuccess(res, file) {
				console.log(res)
                /*if(res.success)
				    this.model.image = res.result.fileUrl*/
                if(res.state == 'SUCCESS'){
	                this.model.image = res.url
                }
			},
			beforeUpload(file) {
				const isLt2M = file.size / 1024 / 1024 < 2
				if (!isLt2M) {
					this.$message.error('上传图片大小不能超过 2MB!')
					return false
				}
				return true
			}
		}
	}
</script>
